import asyncio

from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime

from app.core.config import settings
from app.crud import parameter as crud_parameter
from app.services.weather import weather as weather
from app.services.weather.open_meteo_radiation_fetcher import OpenMeteoRadiationFetcher

async def update_radiation_data():
    today_weather, tomorrow_weather = weather.get_weather()

    print("🔄 正在获取实况天气和短波辐射数据...")
    print(settings.LATITUDE, settings.LONGITUDE)
    fetcher = OpenMeteoRadiationFetcher(latitude=settings.LATITUDE, longitude=settings.LONGITUDE)
    date_str = datetime.now().strftime("%Y-%m-%d")  # 今天
    result = fetcher.get_hourly_radiation(date_str)
    today_radiation = result["next_24_hours_radiation"]
    tomorrow_radiation = result["next_day_radiation"]

    await crud_parameter.update_radiation_data(today_radiation,tomorrow_radiation)
    await crud_parameter.update_wind_data(today_weather,tomorrow_weather)
    print("✅ 数据更新完成\n")

# 启动定时器
def start_scheduler():
    scheduler = BackgroundScheduler()

    def run_async_job():
        asyncio.run(update_radiation_data())

    scheduler.add_job(run_async_job, 'cron', minute=0)
    scheduler.start()
    print("✅ 定时任务已启动")
